package com.tsingteng.cosfun.ui.mine;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.qiniu.android.storage.UploadManager;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.base.BaseFragment;
import com.tsingteng.cosfun.bean.BaseDataBean;
import com.tsingteng.cosfun.bean.PersonBean;
import com.tsingteng.cosfun.bean.VideoSignBean;
import com.tsingteng.cosfun.ui.cosfun.contract.PersonEditContract;
import com.tsingteng.cosfun.ui.cosfun.presenter.PersonEditPresenter;
import com.tsingteng.cosfun.utils.AppUtils;
import com.tsingteng.cosfun.utils.ConvertUtils;
import com.tsingteng.cosfun.utils.DateUtils;
import com.tsingteng.cosfun.utils.ImageUtils;
import com.tsingteng.cosfun.utils.ImageViewUtils;
import com.tsingteng.cosfun.utils.LogonUtils;
import com.tsingteng.cosfun.utils.PhotoUtils;
import com.tsingteng.cosfun.utils.SPUtils;
import com.tsingteng.cosfun.utils.ToastUtils;
import com.tsingteng.cosfun.widget.dialog.BottomListDialog;
import com.tsingteng.cosfun.widget.picker.AddressPickTask;
import com.tsingteng.cosfun.widget.picker.City;
import com.tsingteng.cosfun.widget.picker.County;
import com.tsingteng.cosfun.widget.picker.DatePicker;
import com.tsingteng.cosfun.widget.picker.Province;


import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

import static android.app.Activity.RESULT_OK;


/**
 * author :zhikuan
 * Date:18-8-9
 */
public class PersonInfoFragment extends BaseFragment implements View.OnClickListener, PersonEditContract.IPersonEditView {
    private PersonEditPresenter personEditPresenter;
    private String headUrl;
    private CircleImageView headView;
    private TextView accountId, sex, birthday, address;
    private EditText nickname, sign;
    private boolean isModifier = false;//是否已经校验了图像
    boolean mSignFocus = false;
    private String mBirthday, mAddress;
    private int mSex;
    boolean mNameFocus = false;
    private String mSign;
    private BottomListDialog dialog;
    private String imagePath;
    private String url;

    @Override
    protected void initView() {
        headView = rootView.findViewById(R.id.header_image);
        nickname = rootView.findViewById(R.id.nickname_content);
        accountId = rootView.findViewById(R.id.account_content);
        sex = rootView.findViewById(R.id.sex_content);
        birthday = rootView.findViewById(R.id.birthday_content);
        address = rootView.findViewById(R.id.address_content);
        sign = rootView.findViewById(R.id.sign);
        headView.setOnClickListener(this);
        rootView.findViewById(R.id.id_account).setOnClickListener(this);
        nickname.setOnClickListener(this);
        rootView.findViewById(R.id.header_layout).setOnClickListener(this);

        rootView.findViewById(R.id.birthday).setOnClickListener(this);
        rootView.findViewById(R.id.sex).setOnClickListener(this);
        rootView.findViewById(R.id.address).setOnClickListener(this);

        birthday.setOnClickListener(this);
        sex.setOnClickListener(this);
        address.setOnClickListener(this);
        dialog = new BottomListDialog(getContext());
        List<String> mList = new ArrayList<>();
        mList.clear();
        mList.add("从相册选择");
        mList.add("拍照");
        dialog.setList(mList);
        initListener();
        personEditPresenter = new PersonEditPresenter(this);
        personEditPresenter.getPersonInfo(LogonUtils.getProFildId());
    }
    void initListener(){
        nickname.setOnKeyListener((v, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                String userInput = nickname.getText().toString().trim();
                if (TextUtils.isEmpty(userInput)) {
                    return true;
                }
                personEditPresenter.editUserInfo("nickName", nickname.getText().toString());
                return true;
            }
            return false;
        });


        nickname.setOnFocusChangeListener((v, hasFocus) -> {

            if (!hasFocus && mNameFocus) {
                if (TextUtils.equals(mNickName, nickname.getText().toString())) return;
                mNameFocus =false;
                personEditPresenter.editUserInfo("nickName", nickname.getText().toString());
            }
        });

        sign.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus &&mSignFocus) {
                if (TextUtils.equals(mSign, sign.getText().toString()))return;
                mSignFocus =false;
                personEditPresenter.editUserInfo("signature", sign.getText().toString());
            }
        });




        sign.setOnKeyListener((v, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                String userInput = sign.getText().toString().trim();
                if (TextUtils.isEmpty(userInput)) {
                    return true;
                }
                personEditPresenter.editUserInfo("signature", sign.getText().toString());
                return true;
            }
            return false;
        });
        sign.addTextChangedListener(new TextWatcher() { //对EditText进行监听
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                mSignFocus = true;
                if (sign.getText().toString().length() >= 35) {
                    ToastUtils.showToast("最多输入35个字符！");
                }
            }
        });
        dialog.setOnClickBottomListListener(new BottomListDialog.OnClickBottomListListener() {
            @Override
            public void onClickItem(BaseQuickAdapter adapter, View view, int position, List<String> list) {
                switch (list.get(position)){
                    case "拍照":
                        ImageViewUtils.starShoot(PersonInfoFragment.this, true);
                        break;
                    case "从相册选择":
                        ImageViewUtils.starShoot(PersonInfoFragment.this, false);
                        break;
                }
            }

            @Override
            public void onClickBottom() {
                dialog.dissMiss();
            }
        });
    }

    @Override
    protected void getBundle(Bundle bundle) {

    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_personinfo_layout;
    }

    private Uri imageUri = null;
//    private Uri cropImageUri = null;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.nickname_content:
                mNameFocus =true;
                break;
            case R.id.header_image:
            case R.id.header_layout:
                dialog.show();
//                if (null == getActivity()){
//                    return;
//                }
//                File file = new File(VideoUtils.photoSavePathCache, System.currentTimeMillis() + ".png");
//                if (PhotoUtils.hasSdcard()) {
//                    imageUri = Uri.fromFile(file);
//                    //通过FileProvider创建一个content类型的Uri
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                        imageUri = FileProvider.getUriForFile(getActivity(), PhotoUtils.AUTH, file);
//                    }
//                    PhotoUtils.getInstance().showPopupWindow(getActivity(), rootView, imageUri);
//                } else {
//                    ToastUtils.showToast("设备没有SD卡！");
//                }

                break;

            case R.id.sex_content:
            case R.id.sex:
                showPopupWindow(sex);
                break;
            case R.id.birthday_content:
            case R.id.birthday:
                onYearMonthDayPicker();
                break;
            case R.id.address_content:
            case R.id.address:
                onAddressPicker();
                break;

        }
    }


    /**
     */
    public void onAddressPicker() {
        AddressPickTask task = new AddressPickTask(getActivity());
        task.setHideProvince(false);
        task.setHideCounty(true);
        task.setCallback(new AddressPickTask.Callback() {
            @Override
            public void onAddressInitFailed() {
                showToast("数据初始化失败");
            }

            @Override
            public void onAddressPicked(Province province, City city, County county) {
                if (county == null) {
                    mAddress = city.getAreaId();
                } else {
                    mAddress = province.getAreaId() + city.getAreaId() + county.getAreaId();
                }
                personEditPresenter.editUserInfo("areaid", mAddress);
                address.setText(city.getAreaName());
            }
        });
        task.execute("北京", "北京", "东城区");
    }


    /**
     * 生日选择
     *
     */
    public void onYearMonthDayPicker() {
        if (null ==getActivity()){
            return;
        }
        final DatePicker picker = new DatePicker(getActivity());
        picker.setCanceledOnTouchOutside(true);
        picker.setUseWeight(true);
        picker.setTopPadding(ConvertUtils.toPx(getActivity(), 10));
        //获取系统的日期
        Calendar calendar = Calendar.getInstance();
        //年
        int year = calendar.get(Calendar.YEAR);
        //月
        int month = calendar.get(Calendar.MONTH) + 1;
        //日
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        picker.setRangeEnd(year, month, day);
        picker.setRangeStart(1900, 1, 1);
        if (mBirthday != null && mBirthday.contains("-")) {
            String[] ss = mBirthday.split("-");
            if (ss.length == 3) {
                picker.setSelectedItem(Integer.parseInt(ss[0]), Integer.parseInt(ss[1]), Integer.parseInt(ss[2]));
            } else {
                picker.setSelectedItem(1991, 6, 15);
            }
        } else {
            picker.setSelectedItem(1991, 6, 15);
        }
        picker.setResetWhileWheel(false);
        picker.setOnDatePickListener((DatePicker.OnYearMonthDayPickListener) (year1, month1, day1) -> {
            showToast(year1 + "-" + month1 + "-" + day1);
            mBirthday = year1 + "-" + month1 + "-" + day1;
            birthday.setText(mBirthday);
            personEditPresenter.editUserInfo("birthday", mBirthday);
        });
        picker.setOnWheelListener(new DatePicker.OnWheelListener() {
            @Override
            public void onYearWheeled(int index, String year) {
//                picker.setTitleText(year + "-" + picker.getSelectedMonth() + "-" + picker.getSelectedDay());
            }

            @Override
            public void onMonthWheeled(int index, String month) {
//                picker.setTitleText(picker.getSelectedYear() + "-" + month + "-" + picker.getSelectedDay());
            }

            @Override
            public void onDayWheeled(int index, String day) {
//                picker.setTitleText(picker.getSelectedYear() + "-" + picker.getSelectedMonth() + "-" + day);
            }
        });
        picker.show();
    }

    /***************** 性别弹出 *****************************/

    private PopupWindow popWindow;


    @SuppressWarnings("deprecation")
    private void showPopupWindow(View parent) {
        if (null == getActivity()){
            return;
        }
        if (popWindow == null) {
            LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            if (null == layoutInflater){
                return;
            }
            View view = layoutInflater.inflate(R.layout.pop_sex_select_photo, null);
            popWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT,
                    true);
            initPop(view);
        }

        popWindow.setAnimationStyle(android.R.style.Animation_InputMethod);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        popWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);

    }

    /**
     * 初始化弹窗
     *
     * @param view
     */
    public void initPop(View view) {
        view.setOnClickListener(v -> popWindow.dismiss());
        view.findViewById(R.id.man).setOnClickListener(arg0 -> {
            sex.setText("男");
            mSex = 2;
            popWindow.dismiss();
            personEditPresenter.editUserInfo("sex", mSex + "");

        });
        view.findViewById(R.id.woman).setOnClickListener(arg0 -> {
            popWindow.dismiss();
            sex.setText("女");
            mSex = 1;
            personEditPresenter.editUserInfo("sex", mSex + "");
        });
        view.findViewById(R.id.unknow).setOnClickListener(arg0 -> {
            popWindow.dismiss();
            sex.setText("不确定");
            mSex = 3;
            personEditPresenter.editUserInfo("sex", mSex + "");
        });
        view.findViewById(R.id.secrecy).setOnClickListener(arg0 -> {
            popWindow.dismiss();
            sex.setText("保密");
            mSex = 4;
            personEditPresenter.editUserInfo("sex", mSex + "");
        });
        view.findViewById(R.id.cancel).setOnClickListener(arg0 -> popWindow.dismiss());
    }


    /**
     * 图片选择及拍照结果
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (resultCode != Activity.RESULT_OK) {
//            return;
//        }
//        switch (requestCode) {
//            case PhotoUtils.CODE_GALLERY_REQUEST:// 相册
//                if (null == getActivity()){
//                    return;
//                }
//                if (PhotoUtils.hasSdcard()) {
//                    File file = new File(VideoUtils.photoSavePathCache, System.currentTimeMillis() + ".png");
//                    cropImageUri = Uri.fromFile(file);
//                    Uri newUri = Uri.parse(PhotoUtils.getPath(getActivity(), data.getData()));
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                        newUri = FileProvider.getUriForFile(getActivity(), PhotoUtils.AUTH, new File(newUri.getPath()));
//                    }
//                    PhotoUtils.cropImageUri(getActivity(), newUri, cropImageUri);
//                } else {
//                    ToastUtils.showToast("设备没有SD卡！");
//                }
//                break;
//            case PhotoUtils.CODE_CAMERA_REQUEST:// 拍照
//                File file = new File(VideoUtils.photoSavePathCache, System.currentTimeMillis() + ".png");
//                cropImageUri = Uri.fromFile(file);
//                PhotoUtils.cropImageUri(getActivity(), imageUri, cropImageUri);
//                break;
//            default:
//                personEditPresenter.getSignTureData("1");
//                break;
//        }
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    LocalMedia localMedia = selectList.get(0);
                    if (localMedia.isCut()) {
                        imagePath = localMedia.getCutPath();
                    } else if (localMedia.isCompressed()) {
                        imagePath = localMedia.getCompressPath();
                    } else {
                        imagePath = localMedia.getPath();
                    }
                    SPUtils.init().putString("headUrl", imagePath);
                    Glide.with(this).load(new File(imagePath)).into(headView);
                    personEditPresenter.getSignTureData("1");
                    break;
            }
        }
    }


    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
         if (null == getActivity()){
             return;
         }
        switch (requestCode) {
            case PhotoUtils.CAMERA_PERMISSIONS_REQUEST_CODE: {//调用系统相机申请拍照权限回调
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    PhotoUtils.takePicture(getActivity(), imageUri, PhotoUtils.CODE_CAMERA_REQUEST);
                } else {
                    ToastUtils.showToast("请允许打开相机！！");
                }
                break;


            }
            case PhotoUtils.STORAGE_PERMISSIONS_REQUEST_CODE://调用系统相册申请Sdcard权限回调
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    PhotoUtils.openPic(getActivity(), PhotoUtils.CODE_GALLERY_REQUEST);
                } else {
                    ToastUtils.showToast("请允许打操作SDCard！！");
                }
                break;
        }
    }

    private String mNickName;

    @Override
    public void showLogonResult(BaseDataBean<PersonBean> personBeanBaseDataBean) {
        if (personBeanBaseDataBean == null || personBeanBaseDataBean.data == null) {
            return;
        }
        PersonBean.PersonData data = personBeanBaseDataBean.data.profile;
        url = SPUtils.init().getString("headUrl");
        if (!isModifier && !TextUtils.isEmpty(url)) {//如果地址不为空,说明在个人中心已经修改了,所以重新上传一下
            imagePath = url;
            personEditPresenter.getSignTureData("1");
            isModifier = true;
            SPUtils.init().putString("headUrl", "");
        }else {
            if (!TextUtils.isEmpty(data.image)) { //头像
                if (null == getActivity()) {
                    return;
                }
                Glide.with(getActivity()).load(data.image).into(headView);
            } else {
                ImageUtils.LoadImage(getContext(), "", headView);
            }
        }
        if (!TextUtils.isEmpty(data.nickName)) {
            mNickName = data.nickName;
            nickname.setText(data.nickName);
        }
        if (!TextUtils.isEmpty(nickname.getText())) {
            nickname.setSelection(nickname.getText().length());
        }
        if (!TextUtils.isEmpty(data.id)) {
            accountId.setText(data.id);
        }
        if (!TextUtils.isEmpty(DateUtils.longToString(data.birthday, "yyyy-MM-dd"))) {
            mBirthday = DateUtils.longToString(data.birthday, "yyyy-MM-dd");
            if (0 !=data.birthday) {
                birthday.setText(mBirthday);
            }else{
                birthday.setText("未填写");
            }
        }
    /*    if (!TextUtils.isEmpty(AppUtils.getCityName(getActivity(), data.areaid))) {
            address.setText(getCity(data.areaid));
        }*/
    if (!TextUtils.isEmpty(data.areaid)&&!"0".equals(data.areaid)){
            address.setText(AppUtils.getCityName(getContext(), data.areaid));
        }else{
        address.setText("未填写");
    }

        switch (data.sex) { //1男2女3不确定4保密
            case 1:
                mSex = data.sex;
                sex.setText("女");
                break;
            case 2:
                sex.setText("男");
                break;
            case 3:
                sex.setText("不确定");
                break;
            case 4:
                sex.setText("保密");
                break;
            default:
                sex.setText("未填写");
                break;
        }
        if (!TextUtils.isEmpty(data.signature)) {
        this.mSign  = data.signature;
            sign.setText(data.signature);
        }

    }


//    private String getCity(String id) {
//        ArrayList<Province> data = new ArrayList<>();
//        try {
//            Activity activity = getActivity();
//            if (activity != null) {
//                String json = ConvertUtils.toString(activity.getAssets().open("city.json"));
//
//
//                //Json的解析类对象
//                JsonParser parser = new JsonParser();
//                //将JSON的String 转成一个JsonArray对象
//                JsonArray jsonArray = parser.parse(json).getAsJsonArray();
//
//                Gson gson = new Gson();
//                //加强for循环遍历JsonArray
//                for (JsonElement user : jsonArray) {
//                    //使用GSON，直接转成Bean对象
//                    Province userBean = gson.fromJson(user, Province.class);
//                    data.add(userBean);
//                }
//
//                for (Province province : data) {
//                    for (City city : province.getCities()) {
//                        if (city.getProvinceId().equals(id)) {
//                            return province.getName() + " " + city.getName();
//                        }
//                    }
//                }
//            }
//        } catch (java.io.IOException e) {
//            e.printStackTrace();
//        }
//        return "";
//    }

    @Override
    public void showEditResult(BaseDataBean personBeanBaseDataBean) {
        if (personBeanBaseDataBean == null) {
            return;
        }
        if (personBeanBaseDataBean.getStatus() == 200) {
            if (isModifier) return;
            ToastUtils.showToast("保存成功");
            mNickName = nickname.getText().toString();
            mSign = sign.getText().toString();
        }else if (10005 == personBeanBaseDataBean.getStatus()){
            showToast(personBeanBaseDataBean.getMsg());
        }else {
            ToastUtils.showToast("保存失败");
        }
    }

    @Override
    public void UploadVideo(VideoSignBean data) {
        UploadManager uploadManager = new UploadManager();
        if (null == getActivity()){
            return;
        }
        uploadManager.put(imagePath,
                String.valueOf(LogonUtils.getProFildId() + System.currentTimeMillis()).hashCode() + data.getPath(),
                data.getSign(), (key, info, response) -> getActivity().runOnUiThread(() -> {
                    if (info.isOK()) {
//                                    headUrl = PhotoUtils.URL_IMG + "/" + key;
                        headUrl = data.getDomain() + "/" + key;
                        if (!isModifier) {
                            ToastUtils.showToast("上传成功");
                        }
                        Glide.with(getActivity()).load(headUrl).into(headView);
                        personEditPresenter.editUserInfo("image", headUrl);
                    } else {
                        ToastUtils.showToast(info.error);
                    }
                }), null);
    }

    @Override
    public void showLoading(String msg) {
        showLoadingDialog();
    }

    @Override
    public void hideLoading() {
        hideLoadingDialog();
    }

    @Override
    public void showFail(String msg) {

    }

    @Override
    public void showError() {

    }

    @Override
    public void showEmpty() {

    }


}
